package interceptor;

import config.JwtConfig;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(RequestMethod.OPTIONS.name().equals(request.getMethod())){//放行post get delete put ...
            return true;
 }
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setContentType("application/json;charset=utf-8");
        /** Token 验证 */
        String token = request.getHeader(jwtConfig.getHeader());
        if(ObjectUtils.isEmpty(token)){
            PrintWriter printWriter=response.getWriter();
            printWriter.println(jwtConfig.getHeader()+"不能为空");
            printWriter.flush();
            return false;
        }

        Claims claims = null;
        try{
            claims = jwtConfig.getTokenClaim(token);
            if(claims == null || jwtConfig.isTokenExpired(claims.getExpiration())){
                PrintWriter printWriter=response.getWriter();
                printWriter.println(jwtConfig.getHeader()+"已失效,请重新登录");
                printWriter.flush();
                return false;
            }
        }catch (Exception e){
            PrintWriter printWriter=response.getWriter();
            printWriter.println(jwtConfig.getHeader()+"已失效,请重新登录");
            printWriter.flush();
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
